<?php

/**
 * This is the model class for table "post".
 *
 * The followings are the available columns in table 'post':
 * @property integer $id
 * @property string $type
 * @property string $created_at
 * @property string $updated_at
 */
class Post extends CActiveRecord {

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Post the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'post';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('type', 'length', 'max' => 255),
            array('created_at, updated_at', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, type, created_at, updated_at', 'safe', 'on' => 'search'),
        );
    }

    /**
     * set timestamp before save
     */
    public function beforeSave() {
        if ($this->isNewRecord)
            $this->created_at = new CDbExpression('NOW()');
        $this->updated_at = new CDbExpression('NOW()');
        return parent::beforeSave();
    }

    /**
     * delete all post details and post images before
     */
    public function beforeDelete() {
        PostDetail::model()->deleteAllByPostID($this->id);
        PostImage::model()->deleteAllByPost($this);
        return parent::beforeDelete();
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'postDetails' => array(self::HAS_MANY, 'PostDetail', 'post_id'),
            'postImages' => array(self::HAS_MANY, 'PostImage', 'post_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => Yii::t('post', 'id'),
            'type' => Yii::t('post', 'type'),
            'created_at' => Yii::t('post', 'createdAt'),
            'updated_at' => Yii::t('post', 'updatedAt'),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('type', $this->type, true);
        $criteria->compare('created_at', $this->created_at, true);
        $criteria->compare('updated_at', $this->updated_at, true);

        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                ));
    }

    /**
     * get PostDetail corresponding language 
     * @return PostDetail
     */
    public function getPostDetail($language) {
        $result = null;
        if ($language != null) {
            $id = $this->id;
            $postDetails = $this->postDetails;
            foreach ($postDetails as $postDetail) {
                if ($postDetail->language == $language) {
                    $result = $postDetail;
                }
            }
        }
        return $result;
    }

    /**
     * get PostDetail corresponding language 
     * @return PostDetail
     */
    public function postDetail() {
        $language = Yii::app()->session['language'];
        if (!isset($language)) {
            $language = 'vi';
        }
        $result = null;
        $id = $this->id;
        $postDetails = $this->postDetails;
        foreach ($postDetails as $postDetail) {
            if ($postDetail->language == $language) {
                $result = $postDetail;
            }
        }
        return $result;
    }

    public function findAboutPost($excerpt = false) {
        if ($excerpt) {
            $title = '_about_excerpt_';
        } else {
            $title = '_about_';
        }

        // create creteira object
        $criteria = new CDbCriteria;
        $criteria->alias = 'p';
        $criteria->distinct = true;
        $criteria->join = 'left join post_detail pd on p.id = pd.post_id ' .
                'left join post_image pi on p.id = pi.post_id';

        $criteria->addCondition(array('pd.language = :language',
            'pd.title = :title'));
        $criteria->params = array(':language' => Yii::app()->language,
            ':title' => $title);

        $data = array();
        $results = Post::model()->findAll($criteria);
        if ($results == null || count($results) == 0) {
            return $data;
        }

        $post = $results[0];
        $data['id'] = $post->id;

        $details = $post->postDetails;
        if (count($details) > 0) {
            $data['title'] = $details[0]->title;
            $data['content'] = $details[0]->content;
        }

        if ($excerpt) {
            $criteria->condition = '';
            $criteria->addCondition(array('pd.language = :language',
                'pd.title = :title'));
            $criteria->params = array(':language' => Yii::app()->language,
                ':title' => '_about_');

            $results = Post::model()->findAll($criteria);
            if ($results != null && count($results) >= 0) {
                $images = $results[0]->postImages;
                if (count($images) > 0) {
                    $data['image'] = $images[0]->path;
                }
            }
        }

        return $data;
    }
    
    public function getPostByTitle($title) {

        // create creteira object
        $criteria = new CDbCriteria;
        $criteria->alias = 'p';
        $criteria->distinct = true;
        $criteria->join = 'left join post_detail pd on p.id = pd.post_id and p.type is not null ' ;
               // .'left join post_image pi on p.id = pi.post_id';

        $criteria->addCondition(array('pd.title = :title'));
        $criteria->params = array(':title' => $title);

        $post;
        $results = Post::model()->findAll($criteria);
        if ($results == null || count($results) == 0) {
            return $post = null;
        }

        $post = $results[0];
        return $post;
    }
}